import LayoutHeader2 from '@/components/LayoutHeader2';
import { matchRoutesGroups } from '@/permissonsRoutes'; //根据routes的配置生成对应的路由
import { getPermissions } from '@/services/ant-design-pro/login';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { getDvaApp, history } from '@umijs/max';
import { matchRoutes } from 'umi';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
const loginPath = '/user/login'; // 登录页面路由
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 *  初始化某些全局数据的运行时配置
 * */
export async function getInitialState(): Promise<{
  isLogin: boolean; // 是否登录
  currentUser: API.CurrentUser | undefined; // 当前用户信息
  settings?: Partial<LayoutSettings>; // layout 配置
  loading?: boolean; // 全局loading
  // fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  permissons?: any[]; // 用户权限
}> {
  //根据本地token判断是否登录
  const isLogin = localStorage.getItem('token') ? true : false;
  //根据本地token获取用户信息
  const currentUser = JSON.parse(localStorage.getItem('currentUser') as string);

  let permissons = [];
  let functions_groups = [];
  //如果登录了 请求权限
  if (isLogin) {
    const res = await getPermissions();
    if (res.code === 0) {
      functions_groups = res.data?.functions_groups;
      currentUser.functions_groups = functions_groups;
      permissons = matchRoutesGroups(functions_groups); //根据functions_groups生成对应的路由

      //保存用户信息
      localStorage.setItem('currentUser', JSON.stringify(currentUser));
    }
  }
  //如果登录了 但是在登录页，跳转到首页
  if (isLogin && history.location.pathname === loginPath) {
    history.push('/');
  }

  return {
    permissons,
    isLogin,
    currentUser,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

/**
 * @name layout 配置
 * onPageChange(locale) 有布局的页面切换时的回调 如果路由的layout: false,则不会触发onPageChange
 * onPageChange里可以使用useDispatch和useSelector来修改和获取dva的state
 * @doc https://procomponents.ant.design/components/layout
 */
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  // const dispatch = useDispatch();
  // const headerModel = useSelector((state: any) => {
  //   return state.headerModel;
  // });
  return {
    menuRender: false,
    headerRender: () => {
      return <LayoutHeader2 />;
    },
    // headerRender: false,
    logo: false,
    ...initialState?.settings,
    //布局页面切换时的回调
    onPageChange: () => {
      const { isLogin } = initialState || {};
      const token = localStorage.getItem('token');
      // 如果没有登录，又不在登录页，或者没有token 跳转到登录页面 并带上redirect
      if ((!isLogin && history.location.pathname !== loginPath) || !token) {
        localStorage.removeItem('currentUser');
        localStorage.removeItem('token');
        history.push(`${loginPath}?redirect=${history.location.pathname}`);
      }
    },
  };
};

/**
 * @param  location,routes,clientRoutes
 * onRouteChange 切换路由时触发 等于vue的全局路由守卫
 * onRouteChange、useEffect、onPageChange三者的先后顺序为：onRouteChange -> useEffect -> onPageChange
 * 注意(坑) onRouteChange里要使用dva的dispatch 需要在app.tsx里面引入dvaApp 无法直接使用useDispatch
 */
export const onRouteChange = ({ location, clientRoutes }) => {
  const currentRoute = matchRoutes(clientRoutes, location.pathname)?.pop()?.route;
  const name = currentRoute?.name;
  //在路由跳转时修改headerModel的title和重置rightCon
  getDvaApp()._store.dispatch({
    type: 'headerModel/resetHeader',
    payload: {
      title: name,
      rightCon: null,
    },
  });
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
